package com.shanjupay.common.utilbak;

import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件工具类
 *
 * @author Administrator
 * @version [v1.0, 2012-7-5]
 * @see
 * @since
 */
public class FileUtils {
    /**
     * 创建文件夹
     *
     * @param filePath
     * @return
     * @since <IVersion>
     */
    public static boolean createDir(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return file.mkdir();
        }
        return true;
    }

    /**
     * 文件复制
     *
     * @param sorceFile 源文件
     * @param newFile   目标文件
     * @since <IVersion>
     */
    public static void copyFile(File sorceFile, File newFile) {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(sorceFile);
            os = new FileOutputStream(newFile);
            byte buffer[] = new byte[8192];
            int count = 0;
            while ((count = is.read(buffer)) > 0) {
                os.write(buffer, 0, count);
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
            }
        }

    }

    /**
     * 读取文件获得文件编码格式
     *
     * @param file
     * @return
     */
    public static String getCharset(File file) {
        String charset = "GBK";
        byte[] first3Bytes = new byte[3];
        BufferedInputStream bis = null;
        InputStream in = null;
        try {
            boolean checked = false;
            in = new FileInputStream(file);
            bis = new BufferedInputStream(in);
            bis.mark(0);
            int read = bis.read(first3Bytes, 0, 3);
            if (read == -1)
                return charset;
            if (first3Bytes[0] == (byte) 0xFF && first3Bytes[1] == (byte) 0xFE) {
                charset = "UTF-16LE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xFE
                    && first3Bytes[1] == (byte) 0xFF) {
                charset = "UTF-16BE";
                checked = true;
            } else if (first3Bytes[0] == (byte) 0xEF
                    && first3Bytes[1] == (byte) 0xBB
                    && first3Bytes[2] == (byte) 0xBF) {
                charset = "UTF-8";
                checked = true;
            }
            bis.reset();
            if (!checked) {
                while ((read = bis.read()) != -1) {
                    if (read >= 0xF0)
                        break;
                    if (0x80 <= read && read <= 0xBF) // 单独出现BF以下的，也算是GBK
                        break;
                    if (0xC0 <= read && read <= 0xDF) {
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF)// 双字节 (0xC0 - 0xDF)
                            // (0x80 -
                            // 0xBF),也可能在GB编码内
                            continue;
                        else
                            break;
                    } else if (0xE0 <= read && read <= 0xEF) {// 也有可能出错，但是几率较小
                        read = bis.read();
                        if (0x80 <= read && read <= 0xBF) {
                            read = bis.read();
                            if (0x80 <= read && read <= 0xBF) {
                                charset = "UTF-8";
                                break;
                            } else
                                break;
                        } else
                            break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return charset;
    }

    /**
     * 将字符串写入指定文件
     *
     * @param content  内容
     * @param file     写入的文件
     * @param encoding 字符编码
     * @throws IOException
     * @since <IVersion>
     */
    public static void stringToFile(String content, File file, String encoding)
            throws IOException {
        OutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(content.getBytes(encoding));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            throw e;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    out = null;
                }
            }
        }
    }

    /**
     * 获取年月日路径字符串
     *
     * @return
     * @since <IVersion>
     */
    public static String getYYYYMMDDPath() {
        String path = TimeUtils.getDateString("yyyy" + File.separator + "MM"
                + File.separator + "dd");
        return path;
    }

    /**
     * 列出目录下的所有文件
     *
     * @param dir
     * @return
     * @since <IVersion>
     */
    public static List<File> listAllFile(String dir) {
        if (StringUtils.isEmpty(dir)) {
            return null;
        }
        List<File> fileList = new ArrayList<File>();
        File file = new File(dir);
        getFile(fileList, file);
        return fileList;
    }

    /**
     * 列出目录下的所有文件
     *
     * @param dir
     * @return
     * @since <IVersion>
     */
    public static List<File> listBatchAllFile(String dir) {
        if (StringUtils.isEmpty(dir)) {
            return null;
        }
        List<File> fileList = new ArrayList<File>();
        File file = new File(dir);
        getBacthFile(fileList, file);
        return fileList;
    }

    /**
     * 列出目录下的所有文件
     *
     * @param dir
     * @return
     * @since <IVersion>
     */
    public static List<File> listAllFile(String dir, List<File> listDeleteFile, boolean result) {
        List<File> fileList = new ArrayList<File>();
        List<File> tempList = new ArrayList<File>();
        if (result) {
            if (StringUtils.isEmpty(dir)) {
                return null;
            }

            File fileTemp = new File(dir);
            getFile(fileList, fileTemp);

            for (File file : fileList) {
                String fileName = file.getName();
                String path = file.getParent();
                int index = fileName.lastIndexOf(".");
                String fileType = fileName.substring(index + 1);
                if ("doc".equalsIgnoreCase(fileType)
                        || "docx".equalsIgnoreCase(fileType)
                        || "txt".equalsIgnoreCase(fileType)
                        || "zip".equalsIgnoreCase(fileType)
                        || "rar".equalsIgnoreCase(fileType)
                        || "pdf".equalsIgnoreCase(fileType)) {
                    tempList.add(file);
                } else {
                    listDeleteFile.add(file);
                    file.delete();
                }
            }
        }

        return tempList;


    }

    /**
     * 列出目录下的所有文件
     *
     * @param dir
     * @return
     * @since <IVersion>
     */
    public static void listAllFile(String dir, boolean result, List<String> beanNames, List<File> returnfileList) {
        List<File> fileList = new ArrayList<File>();
        if (result) {
            File fileTemp = new File(dir);
            getFile(fileList, fileTemp);
            for (File file : fileList) {
                String fileNametemp = file.getName();

                for (String o : beanNames) {
                    if (fileNametemp.equals(o)) {
                        returnfileList.add(file);

                    }
                }

            }
        }

    }

    /**
     * 递归读取文件信息
     *
     * @param fileList
     * @param file
     * @since <IVersion>
     */
    public static void getBacthFile(List<File> fileList, File file) {
        if (file.isDirectory()) {
            File[] temp = file.listFiles();
            for (File tempFile : temp) {
                System.out.println(tempFile.getName());
                getBacthFile(fileList, tempFile);
            }
        } else {
            String suffi = getSuffixe(file.getName());
            if (isKnowledge(suffi)) {
                fileList.add(file);
            }
        }

    }


    /**
     * 递归读取文件信息
     *
     * @param fileList
     * @param file
     * @since <IVersion>
     */
    public static void getFile(List<File> fileList, File file) {
        if (file.isDirectory()) {
            File[] temp = file.listFiles();
            for (File tempFile : temp) {
                getFile(fileList, tempFile);
            }
        } else {
        	/*String suffi = getSuffixe(file.getName());
        	if (isKnowledge(suffi)) {
        		fileList.add(file);
        	}*/
            fileList.add(file);
        }

    }

    /**
     * 将文件目录结构转换为可用的目录结构
     *
     * @param filePath
     * @return
     * @since <IVersion>
     */
    public static String toFilePath(String filePath) {
        return filePath.replace("/", File.separator);
    }

    /**
     * 输出文件
     *
     * @param outputFile 输出文件路径
     * @param fileType   输出文件类型
     * @param fileTitle  输出文件名称
     * @param response   响应
     * @throws Exception
     * @since <IVersion>
     */
    public static void doFile(String outputFile, String fileType,
                              String fileTitle, HttpServletResponse response) {
        doFile(new File(outputFile), fileType, fileTitle, response);
    }

    /**
     * 输出文件
     *
     * @param file      输出文件路径
     * @param fileType  输出文件类型
     * @param fileTitle 输出文件名称
     * @param response  响应
     * @throws Exception
     * @since <IVersion>
     */
    public synchronized static void doFile(File file, String fileType, String fileTitle,
                                           HttpServletResponse response) {
        String CONTENT_TYPE = "application/pdf;charset=GBK";
        OutputStream out = null;
        InputStream is = null;
        try {
            String fileName = new String(fileTitle.getBytes("UTF-8"), "ISO8859_1");
            String s = "inline; filename=" + fileName + fileType;
            response.setContentType(CONTENT_TYPE);
            response.setContentType("application/vnd.ms-excel;");
            response.setHeader("Content-Disposition", s);
            out = response.getOutputStream();
            is = new BufferedInputStream(new FileInputStream(file));
            byte[] buf = new byte[1024];
            int count = 0;
            while ((count = is.read(buf)) > 0) {
                out.write(buf, 0, count);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 输出文件
     *
     * @param file      输出文件路径
     * @param fileType  输出文件类型
     * @param fileTitle 输出文件名称
     * @param response  响应
     * @throws Exception
     * @since <IVersion>
     */
    public synchronized static void doFile2(File file, String fileType, String fileTitle,
                                            HttpServletResponse response, HttpServletRequest request) {
        String CONTENT_TYPE = "application/pdf;charset=GBK";
        //String displayName;
        ServletOutputStream out = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            //displayName = new String(fileTitle.getBytes("GB2312"), "ISO8859_1");
            //MimeUtility.encodeWord(fileTitle);
            String fileName = null;
            String userAgent = request.getHeader("User-Agent");
            //针对IE或者以IE为内核的浏览器：
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = java.net.URLEncoder.encode(fileTitle, "UTF-8");
            } else {
                //非IE浏览器的处理：
                fileName = new String(fileTitle.getBytes("UTF-8"), "ISO-8859-1");
            }
            //String fileName = URLEncoder.encode(fileTitle, "UTF-8");//修复浏览器下载问题  by maoyi

            String s = "inline; filename=" + fileTitle + fileType;
            //response.setContentType(CONTENT_TYPE);
            //response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", s);
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            out = response.getOutputStream();
            is = new BufferedInputStream(new FileInputStream(file));
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
            }
        }
    }

    /**
     * 判断是否为可识别的文件后缀
     *
     * @param fileSuffixes
     * @return
     * @since <IVersion>
     */
    public static boolean isKnowledge(String fileSuffixes) {
        if (".doc".equalsIgnoreCase(fileSuffixes)
                || ".docx".equalsIgnoreCase(fileSuffixes)
                || ".txt".equalsIgnoreCase(fileSuffixes)
                || ".pdf".equalsIgnoreCase(fileSuffixes)
                || ".xls".equalsIgnoreCase(fileSuffixes)) {
            return true;
        }
        return false;
    }


    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     * @since <IVersion>
     */
    public static String getSuffixe(String fileName) {
        int index = fileName.lastIndexOf(".");
        if (index > 0) {
            return fileName.substring(index);
        }
        return "";
    }

    public static void main(String[] arg0) {
        /*List<File> list = listAllFile("F:\\html(2012-7-30)框架");
        for (File file : list)
        {
            System.out.println(file.getPath());
        }*/

        System.out.println(getFileName("111111111.png"));
    }

    public static String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        if (index > 0) {
            return fileName.substring(0, index);
        }
        return "";
    }

    public static String toUtf8String(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("utf-8");
                } catch (Exception ex) {
                    System.out.println(ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) k += 256;
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取文件大小
     *
     * @param file
     * @return
     */
    public static Long getFileSize(File file) {
        Long fileSize = 0L;
        if (file.exists() && file.isFile()) {
            fileSize = file.length();
        }
        return fileSize;
    }

    /**
     * 将文件大小由Byte转为MB或者KB
     *
     * @return
     */
    public static String fileSizeByteToM(Long size) {

        BigDecimal fileSize = new BigDecimal(size);
        BigDecimal param = new BigDecimal(1024);
        int count = 0;
        while (fileSize.compareTo(param) > 0 && count < 5) {
            fileSize = fileSize.divide(param);
            count++;
        }
        DecimalFormat df = new DecimalFormat("#.##");
        String result = df.format(fileSize) + "";
        switch (count) {
            case 0:
                result += "B";
                break;
            case 1:
                result += "KB";
                break;
            case 2:
                result += "MB";
                break;
            case 3:
                result += "GB";
                break;
            case 4:
                result += "TB";
                break;
            case 5:
                result += "PB";
                break;
        }
        return result;
    }

    /**
     * 将文件大小由Byte转为MB或者KB
     * unit : B，KB，MB，GB，TB，PB
     *
     * @return
     */
    public static Float fileSizeByteToMFloat(Long size, String unit) {

        BigDecimal fileSize = new BigDecimal(size);
        BigDecimal param = null;
        switch (unit) {
            case "B":
                param = new BigDecimal(1);
                break;
            case "KB":
                param = new BigDecimal(1024);
                break;
            case "MB":
                param = new BigDecimal(1024 * 1024);
                break;
            case "GB":
                param = new BigDecimal(1024 * 1024 * 1024);
                break;
            case "TB":
                param = new BigDecimal(1024 * 1024 * 1024 * 1024);
                break;
            case "PB":
                param = new BigDecimal(1024 * 1024 * 1024 * 1024 * 1024);
                break;
        }

        fileSize = fileSize.divide(param);
        DecimalFormat df = new DecimalFormat("#.##");
        Float result = Float.parseFloat(df.format(fileSize));
        return result;
    }
}
